package com.tony.blog.server.queue;

import com.tony.blog.api.utils.BlogMsg;
import com.tony.blog.api.utils.Constant;
import com.tony.blog.model.mapper.BlogMapper;
import com.tony.blog.server.lucene.LuceneBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: BlogQueueConsumerV2
 * @Auther: 皮蛋布丁
 * @Date: 2021/09/29/17:03
 * @Description: 内存队列解耦服务核心类
 */
public class BlogQueueConsumerV2 {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private LuceneBlogService luceneBlogService;

    @Scheduled(cron = "0/2 * * * * ?")
    public void listenMsg() {
        try {
            while (Constant.BLOG_Queue.size() > 0) {
                BlogMsg msg = Constant.BLOG_Queue.poll();

                //根据不同的事件类型type执行不同的动作
                if (Objects.equals(msg.getType(),Constant.BlogIndexMsg.Create.getType()) || Objects.equals(msg.getType(),Constant.BlogIndexMsg.Active.getType())) {
                    luceneBlogService.createDocument(blogMapper.selectByPK(msg.getBlogId()));
                } else if (Objects.equals(msg.getType(),Constant.BlogIndexMsg.Delete.getType()) || Objects.equals(msg.getType(),Constant.BlogIndexMsg.UnActive.getType())) {
                    luceneBlogService.deleteDocument(msg.getBlogId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
